// pages/anxiety/index.js
const app = getApp();
const themeManager = require('../../utils/theme-manager');
const { storage } = require('../../utils/storage');

Page({
  data: {
    // 主题相关
    currentTheme: 'pink',
    themeColors: {},
    
    // 用户信息
    userInfo: {},
    
    // 焦虑评估
    anxietyLevel: 0, // 0-10
    anxietyTriggers: [],
    currentMood: '',
    
    // 安抚工具
    tools: [
      {
        id: 'breathing',
        name: '呼吸引导',
        icon: '🫁',
        description: '通过深呼吸练习缓解焦虑',
        color: '#87CEEB',
        path: '/pages/anxiety/breathing',
        duration: '5-15分钟',
        effectiveness: 85
      },
      {
        id: 'sensory',
        name: '感官安抚',
        icon: '🌸',
        description: '通过五感体验回归当下',
        color: '#DDA0DD',
        path: '/pages/anxiety/sensory',
        duration: '3-10分钟',
        effectiveness: 78
      },
      {
        id: 'thinking',
        name: '思维拆解',
        icon: '🧠',
        description: '理性分析焦虑源头',
        color: '#98FB98',
        path: '/pages/anxiety/thinking',
        duration: '10-20分钟',
        effectiveness: 82
      }
    ],
    
    // 快速缓解技巧
    quickTips: [
      {
        id: 'grounding',
        title: '5-4-3-2-1接地法',
        content: '找到5样看到的、4样摸到的、3样听到的、2样闻到的、1样尝到的',
        icon: '🌱',
        duration: '2分钟'
      },
      {
        id: 'muscle',
        title: '肌肉放松',
        content: '从脚趾开始，逐步紧张再放松每个肌肉群',
        icon: '💪',
        duration: '5分钟'
      },
      {
        id: 'visualization',
        title: '安全空间想象',
        content: '闭眼想象一个让你感到安全舒适的地方',
        icon: '🏡',
        duration: '3分钟'
      },
      {
        id: 'affirmation',
        title: '积极自我对话',
        content: '重复积极的自我肯定语句',
        icon: '💝',
        duration: '1分钟'
      }
    ],
    
    // 焦虑触发因素
    triggerOptions: [
      { id: 'work', name: '工作压力', icon: '💼' },
      { id: 'relationship', name: '人际关系', icon: '👥' },
      { id: 'health', name: '健康担忧', icon: '🏥' },
      { id: 'future', name: '未来不确定', icon: '🔮' },
      { id: 'money', name: '经济压力', icon: '💰' },
      { id: 'family', name: '家庭问题', icon: '👨‍👩‍👧‍👦' },
      { id: 'social', name: '社交焦虑', icon: '🎭' },
      { id: 'performance', name: '表现焦虑', icon: '🎯' }
    ],
    
    // 心情选项
    moodOptions: [
      { id: 'panic', name: '恐慌', emoji: '😱', color: '#FF4444' },
      { id: 'anxious', name: '焦虑', emoji: '😰', color: '#FF8800' },
      { id: 'worried', name: '担心', emoji: '😟', color: '#FFAA00' },
      { id: 'nervous', name: '紧张', emoji: '😬', color: '#FFDD00' },
      { id: 'uneasy', name: '不安', emoji: '😕', color: '#88DD00' },
      { id: 'calm', name: '平静', emoji: '😌', color: '#00DD88' }
    ],
    
    // 使用记录
    usageStats: {
      totalSessions: 0,
      favoriteTools: [],
      weeklyProgress: []
    },
    
    // UI状态
    showAssessment: false,
    showQuickTip: false,
    selectedTip: null,
    showStats: false,
    
    // 动画状态
    breathingAnimation: false,
    pulseAnimation: false,
    
    // 加载状态
    loading: true
  },

  onLoad(options) {
    this.initTheme();
    this.loadUserData();
    this.loadUsageStats();
    this.startBreathingAnimation();
    this.setData({ loading: false });
  },

  onShow() {
    this.refreshData();
  },

  // 初始化主题
  initTheme() {
    const userInfo = app.globalData.userInfo || {};
    const theme = userInfo.role === 'male' ? 'gold' : 'pink';
    const colors = themeManager.getThemeColors(theme);
    
    this.setData({
      currentTheme: theme,
      themeColors: colors,
      userInfo
    });
  },

  // 加载用户数据
  loadUserData() {
    // 修复：正确访问存储对象
    const anxietyData = storage.get('anxietyData') || {
      level: 0,
      triggers: [],
      mood: ''
    };
    
    this.setData({
      anxietyLevel: anxietyData.level,
      anxietyTriggers: anxietyData.triggers,
      currentMood: anxietyData.mood
    });
  },

  // 加载使用统计
  loadUsageStats() {
    // 修复：正确访问存储对象
    const stats = storage.get('anxietyStats') || {
      totalSessions: 0,
      favoriteTools: [],
      weeklyProgress: []
    };
    
    this.setData({ usageStats: stats });
  },

  // 刷新数据
  refreshData() {
    this.loadUserData();
    this.loadUsageStats();
  },

  // 开始呼吸动画
  startBreathingAnimation() {
    this.setData({ breathingAnimation: true });
    
    setInterval(() => {
      this.setData({ pulseAnimation: !this.data.pulseAnimation });
    }, 4000);
  },

  // 开始焦虑评估
  onStartAssessment() {
    this.setData({ showAssessment: true });
  },

  // 选择焦虑等级
  onSelectAnxietyLevel(e) {
    const level = parseInt(e.currentTarget.dataset.level);
    this.setData({ anxietyLevel: level });
    
    // 保存数据
    this.saveAnxietyData();
  },

  // 选择触发因素
  onSelectTrigger(e) {
    const trigger = e.currentTarget.dataset.trigger;
    const triggers = [...this.data.anxietyTriggers];
    
    const index = triggers.indexOf(trigger);
    if (index > -1) {
      triggers.splice(index, 1);
    } else {
      triggers.push(trigger);
    }
    
    this.setData({ anxietyTriggers: triggers });
    this.saveAnxietyData();
  },

  // 选择心情
  onSelectMood(e) {
    const mood = e.currentTarget.dataset.mood;
    this.setData({ currentMood: mood });
    this.saveAnxietyData();
  },

  // 保存焦虑数据
  saveAnxietyData() {
    const anxietyData = {
      level: this.data.anxietyLevel,
      triggers: this.data.anxietyTriggers,
      mood: this.data.currentMood,
      timestamp: Date.now()
    };
    
    storage.set('anxietyData', anxietyData);
  },

  // 完成评估
  onCompleteAssessment() {
    this.setData({ showAssessment: false });
    
    // 根据焦虑等级推荐工具
    this.recommendTools();
    
    wx.showToast({
      title: '评估完成',
      icon: 'success'
    });
  },

  // 推荐工具
  recommendTools() {
    const { anxietyLevel } = this.data;
    let message = '';
    
    if (anxietyLevel >= 8) {
      message = '建议先进行呼吸引导，然后尝试感官安抚';
    } else if (anxietyLevel >= 5) {
      message = '可以尝试感官安抚或思维拆解';
    } else if (anxietyLevel >= 3) {
      message = '思维拆解可能对你很有帮助';
    } else {
      message = '你的状态不错，可以尝试任何喜欢的工具';
    }
    
    wx.showModal({
      title: '个性化建议',
      content: message,
      showCancel: false
    });
  },

  // 使用工具
  onUseTool(e) {
    const tool = e.currentTarget.dataset.tool;
    
    // 记录使用
    this.recordToolUsage(tool.id);
    
    // 跳转到工具页面
    wx.navigateTo({
      url: tool.path
    });
  },

  // 记录工具使用
  recordToolUsage(toolId) {
    const stats = { ...this.data.usageStats };
    stats.totalSessions++;
    
    // 更新最喜欢的工具
    const favoriteIndex = stats.favoriteTools.findIndex(item => item.id === toolId);
    if (favoriteIndex > -1) {
      stats.favoriteTools[favoriteIndex].count++;
    } else {
      stats.favoriteTools.push({ id: toolId, count: 1 });
    }
    
    // 排序
    stats.favoriteTools.sort((a, b) => b.count - a.count);
    
    this.setData({ usageStats: stats });
    storage.set('anxietyStats', stats);
  },

  // 显示快速技巧
  onShowQuickTip(e) {
    const tip = e.currentTarget.dataset.tip;
    this.setData({
      showQuickTip: true,
      selectedTip: tip
    });
  },

  // 开始快速技巧
  onStartQuickTip() {
    const { selectedTip } = this.data;
    
    wx.showModal({
      title: selectedTip.title,
      content: `${selectedTip.content}\n\n预计用时：${selectedTip.duration}`,
      confirmText: '开始',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.executeQuickTip();
        }
      }
    });
  },

  // 执行快速技巧
  executeQuickTip() {
    const { selectedTip } = this.data;
    
    // 记录使用
    this.recordToolUsage(`quick_${selectedTip.id}`);
    
    // 显示指导
    wx.showToast({
      title: '开始练习',
      icon: 'success'
    });
    
    this.setData({ showQuickTip: false });
  },

  // 显示统计
  onShowStats() {
    this.setData({ showStats: true });
  },

  // 获取工具名称
  getToolName(toolId) {
    if (toolId.startsWith('quick_')) {
      const tipId = toolId.replace('quick_', '');
      const tip = this.data.quickTips.find(t => t.id === tipId);
      return tip ? tip.title : '快速技巧';
    }
    
    const tool = this.data.tools.find(t => t.id === toolId);
    return tool ? tool.name : '未知工具';
  },

  // 获取焦虑等级描述
  getAnxietyLevelText(level) {
    if (level === 0) return '非常平静';
    if (level <= 2) return '轻微不安';
    if (level <= 4) return '有些担心';
    if (level <= 6) return '明显焦虑';
    if (level <= 8) return '严重焦虑';
    return '极度焦虑';
  },

  // 获取焦虑等级颜色
  getAnxietyLevelColor(level) {
    if (level === 0) return '#00DD88';
    if (level <= 2) return '#88DD00';
    if (level <= 4) return '#DDDD00';
    if (level <= 6) return '#FFAA00';
    if (level <= 8) return '#FF8800';
    return '#FF4444';
  },

  // 获取心情信息的辅助方法
  getCurrentMoodEmoji(currentMood) {
    if (!currentMood) return '';
    const mood = this.data.moodOptions.find(m => m.id === currentMood);
    return mood ? mood.emoji : '';
  },

  getCurrentMoodName(currentMood) {
    if (!currentMood) return '';
    const mood = this.data.moodOptions.find(m => m.id === currentMood);
    return mood ? mood.name : '';
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showAssessment: false,
      showQuickTip: false,
      showStats: false
    });
  },

  // 紧急求助
  onEmergencyHelp() {
    wx.showModal({
      title: '紧急求助',
      content: '如果你正在经历严重的焦虑或恐慌，建议立即寻求专业帮助。\n\n心理援助热线：400-161-9995',
      confirmText: '拨打电话',
      cancelText: '我知道了',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-161-9995'
          });
        }
      }
    });
  },

  // 分享页面
  onShareAnxiety() {
    return {
      title: '焦虑安抚空间 - 找到内心的平静',
      path: '/pages/anxiety/index',
      imageUrl: '/images/anxiety-share.png'
    };
  },

  onShareAppMessage() {
    return this.onShareAnxiety();
  }
});